<template>
  <div class="p-2">
    <div class="mb-[10px]" v-show="showSearch">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入部门名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll"
              >展开/折叠</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="deptTableRef"
        :default-expand-all="isExpandAll"
      >
        <el-table-column prop="id" label="id" width="260"></el-table-column>
        <el-table-column prop="name" align="center" label="名称" width="200"></el-table-column>

        <el-table-column label="pid" align="center" prop="pid" width="200"> </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { delDept, getDept, listCity, listDeptExcludeChild, listUserByDeptId } from '@/apis/city'
import { DeptForm, DeptQuery, DeptVO, UserVO } from '@/apis/types'

interface DeptOptionsType {
  deptId: number | string
  deptName: string
  children: DeptOptionsType[]
}

const initFormData: DeptForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0'
}
const dialog = reactive({
  visible: false,
  title: ''
})

const showSearch = ref(true)
const loading = ref(true)
const deptList = ref<DeptVO[]>([])
const queryFormRef = ref({})
const deptFormRef = ref({})
const form = ref({})
const deptOptions = ref<DeptOptionsType[]>([])
const isExpandAll = ref(true)
const deptTableRef = ref({})
const deptUserList = ref<UserVO[]>([])

const queryParams = reactive<DeptQuery>({
  pageNum: 1,
  pageSize: 10,
  deptName: undefined,
  status: undefined
})

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData }
  deptFormRef.value?.resetFields()
}

/** 新增按钮操作 */
const handleAdd = async (row?: DeptVO) => {
  reset()
  const res = await listCity()
  // TODO: 将返回结果转换成树形结构
  const { data } = res
  if (data) {
    deptOptions.value = data
    if (row && row.deptId) {
      form.value.parentId = row?.deptId
    }
    dialog.visible = true
    dialog.title = '添加部门'
  }
}

/** 查询菜单列表 */
const getList = async () => {
  loading.value = true
  const res = await listCity(queryParams)
  // const data = proxy?.handleTree<DeptVO>(res.data, 'deptId')
  const { data } = res
  if (data) {
    deptList.value = data
  }
  loading.value = false
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  toggleExpandAll(deptList.value, isExpandAll.value)
}

/** 展开/折叠所有 */
const toggleExpandAll = (data: DeptVO[], status: boolean) => {
  data.forEach((item) => {
    deptTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: DeptVO) => {
  reset()
  //查询当前部门所有用户
  getDeptAllUser(row.deptId)
  const res = await getDept(row.deptId)
  form.value = res.data
  const response = await listDeptExcludeChild(row.deptId)
  // const data = proxy?.handleTree<DeptOptionsType>(response.data, 'deptId')
  const data = {}
  if (data) {
    deptOptions.value = data
    if (data.length === 0) {
      const noResultsOptions: DeptOptionsType = {
        deptId: res.data.parentId,
        deptName: res.data.parentName,
        children: []
      }
      deptOptions.value.push(noResultsOptions)
    }
  }
  dialog.visible = true
  dialog.title = '修改部门'
}

/** 查询当前部门的所有用户 */
async function getDeptAllUser(deptId: any) {
  if (deptId !== null && deptId !== '' && deptId !== undefined) {
    const res = await listUserByDeptId(deptId)
    deptUserList.value = res.data
  }
}

/** 删除按钮操作 */
const handleDelete = async (row: DeptVO) => {
  await delDept(row.deptId)
  await getList()
}

onMounted(() => {
  getList()
})
</script>
<style>
.p-2 {
  padding: 2rem;
}
</style>
